<?php
$xml = new SimpleXMLElement("<lvb_system></lvb_system>");
//$xml->addAttribute('encoding','UTF-8');
//Line Element
foreach ($line as $item) {
    //Vehicle Counter
    $count = 0;
    foreach ($vehicle as $count_vehicles) {
        if ($item['id'] == $count_vehicles['line_id']) {
            $count++;
        }
    }
    /////
    $xml_line = $xml->addChild('line');
    $xml_line->addAttribute('id', $item['id']);
    $xml_line->addChild('code', $item['code']);
    $xml_line->addChild('type', $item['type']);
    $xml_line->addChild('start_time_operation', $item['start_time_operation']);
    $xml_line->addChild('end_time_operation', $item['end_time_operation']);
    $xml_line->addChild('count_vehicles', $count);
    $xml_line->addChild('map', $item['map']);
    $start_station = $xml_line->addChild('start_station');
    $end_station = $xml_line->addChild('end_station');
    foreach ($station as $item2) {
        //Add Start-End ID
        if ($item2['position_station'] == 'START') {
            $start_station->addAttribute('id', $item2['id']);     
            $start_station->addChild('name', $item2['name']);                     
        } elseif ($item2['position_station'] == 'END') {
            $end_station->addAttribute('id', $item2['id']);
            $end_station->addChild('name', $item2['name']); 
        }
    }
    foreach ($station as $item2) {
        $count++;
        if ($item2['line_id'] == $item['id'] && $item2['position_station'] == '' || $item2['position_station'] == 'INTER' ) {
            $xml_station = $xml_line->addChild('intermediate_stations');
            $xml_station->addChild('name', $item2['name']);
            $xml_station->addAttribute('id', $item2['id']);            
        }        
    }
    $count =0;
    foreach ($vehicle as $item3) {
        if ($item3['line_id'] == $item['id']) {
            $xml_vehicle = $xml_line->addChild('vehicles_line');
            $xml_vehicle->addChild('name', $item3['name']);
            $xml_vehicle->addChild('capacity', $item3['capacity']);
            $xml_vehicle->addAttribute('id', $item3['id']);            
            foreach ($driver as $item4) {
                if ($item4['vehicle_id'] == $item3['id']) {
                    $xml_driver = $xml_vehicle->addChild('driver');    
                    $xml_driver->addChild('name', $item4['name']);
                    $xml_driver->addChild('birth_date', $item4['birth_date']);
                    $xml_driver->addChild('email', $item4['email']);
                    $xml_driver->addChild('phone', $item4['phone']);
                    $xml_driver->addChild('avatar', $item4['avatar']);
                    $xml_driver->addAttribute('id', $item4['id']); 
                }
            }
        }
    }
}
header('Content-Type: text/xml');
$str = $xml->asXML();



